import {FC, ReactElement, useEffect, useState} from "react";
import {Button, Image, Space, Tag} from "antd";
import {randomColor} from "ts-mango";
import {BookConfig} from "@/apis/recommend";
import {getBookInfoById} from "@/apis/knowledgeGraph";
import {ApiConstants} from "@/apis/constants";
import {errorMessage} from "@/common/components/Message";
import {navigation} from "@/common/components/Navigation";
import {Loading} from "@/common/components/Loading";
import {Store} from "@/common/components/SetScore";

interface Props {
    bookId: string
}

export const Info: FC<Props> = (props) => {
    const {bookId} = props
    const [bookState, setBookState] = useState<BookConfig>()
    const [labels, setLabels] = useState<ReactElement[]>([])

    useEffect(() => {
        /* 加载图书数据 */
        async function loadBookData() {
            const {code, data, msg} = await getBookInfoById(bookId)
            if (code !== ApiConstants.SUCCESS) {
                errorMessage(msg)
                navigation("/index")
                throw new Error()
            }
            setLabels(data.label.map((item, index) => <Tag key={index} color={randomColor()}>{item}</Tag>))
            setBookState(data)
        }

        loadBookData().then()
    }, [bookId])

    return bookState ? (
        <div className="info_card">
            <div className="info_card_right">
                <Image className="info_image" width={240} src={bookState.image}/>
            </div>
            <div className="info_card_left">
                <h2>{bookState.name}</h2>
                <p><b>作者: </b>{bookState.author}</p>
                <p><b>描述: </b>{bookState.abstract}</p>
                <p><b>分类: </b><Tag color={randomColor()}>{bookState.type}</Tag></p>
                <div><b>标签: </b><Space size={[0, 8]} wrap>{labels}</Space></div>
                <div><b>评分: </b><Store allowHalf defaultValue={bookState.score} id={bookId}/></div>
                <Button type="primary" onClick={() => {
                    window.open(bookState.link, "_blank")
                }}>开始阅读</Button>
            </div>
        </div>
    ) : (<Loading/>)
}
